<?php


namespace app\common\util;


use app\common\constants\UrlConstants;
use app\common\exception\HttpRequestException;

class MessageRobot
{
    /**
     * 发送微信机器人消息
     * @param string $key 微信机器人的key
     * @param array $data 要发送的数据
     * @return bool|mixed|string
     */
    public function wechat(string $key, array $data)
    {
        try {
            $url = UrlConstants::WE_CHAT_ROBOT_WEB_HOOK . '?key=' . $key;
            $result = (new HttpRequest([], false))->post($url, $data, true);
            if (!array_key_exists('errcode', $result) || $result['errcode'] !== 0) {
                return $result['errmsg'] ?? '';
            }
            return true;
        } catch (HttpRequestException $e) {
            return $e->getMessage();
        }
    }

    /**
     * 获取微信机器人消息模板
     * @param string $type 消息类型
     * @param array $data 消息数据
     * @return array
     */
    public function getWeChatMsgTpl(string $type, array $data): array
    {
        return [
            'msgtype' => $type,
            $type => $data
        ];
    }

    /**
     * 钉钉发送机器人消息
     * @param string $accessToken url的accessToken
     * @param string $secret 密钥
     * @param array $data 要发送的数据
     * @return bool|mixed|string
     */
    public function dingTalk(string $accessToken, string $secret, array $data)
    {
        try {
            //时间戳
            $timestamp = get_millisecond();

            //生成签名
            $signStr = $timestamp . "\n" . $secret;
            $signStr = base64_encode(hash_hmac('sha256', $signStr, $secret, true));
            $signStr = utf8_encode(urlencode($signStr));

            //生成url地址
            $url = UrlConstants::DING_TALK_ROBOT_WEB_HOOK . '?' . http_build_query([
                    'timestamp' => $timestamp,
                    'sign' => $signStr,
                    'access_token' => $accessToken
                ]);

            //执行请求
            $result = (new HttpRequest([], false))->post($url, $data, true);

            //校验请求结果
            if (!array_key_exists('errcode', $result) || $result['errcode'] !== 0) {
                return $result['errmsg'] ?? '';
            }

            return true;
        } catch (HttpRequestException $e) {
            return $e->getMessage();
        }
    }

    /**
     * 获取钉钉机器人消息模板
     * @param string $type 消息类型
     * @param array $data 消息数据
     * @param array $at 要@的人
     * @return array
     */
    public function getDingTalkMsgTpl(string $type, array $data, array $at = []): array
    {
        return [
            'at' => $at,
            'msgtype' => $type,
            $type => $data
        ];
    }
}